package com.hsj.springai.service;

import com.hsj.springai.utils.MyTask;
import com.hsj.springai.utils.TaskBatchSendUtils;
import io.swagger.v3.oas.annotations.servers.Server;
import jakarta.annotation.Resource;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AsyncService {

    @Resource
    private ThreadPoolTaskExecutor mailThreadPool;

    @Async("mailThreadPool")
    @SneakyThrows
    public void sendEmail(String email, String content) {
        Thread.sleep(new Random().nextInt(3000));
        log.info("线程 {} 发送给{}的邮件发送成功。内容为{}", Thread.currentThread().getName(), email, content);
    }

    //交给那个线程池去执行
    @Async("mailThreadPool")
    //异常try catch 代码可以不用写 lombok自动生成
    @SneakyThrows
    public CompletableFuture<String> blockSendEmail(String email, String content) {
        Thread.sleep(new Random().nextInt(3000));

        if (new Random().nextInt(10) > 5) {
            return CompletableFuture.completedFuture(String.format("线程%s:发送给%s的邮件。内容为%s,发送成功", Thread.currentThread().getName(), email, content));
        } else {
            return CompletableFuture.completedFuture(String.format("线程%s:发送给%s的邮件。内容为%s,发送失败", Thread.currentThread().getName(), email, content));
        }

    }


    public String testAsync() throws InterruptedException {
        //创建任务列表
        ArrayList<MyTask> myTasks = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            MyTask myTask = new MyTask();
            myTask.setTaskName("任务" + i);
            myTask.setTaskContent("执行了" + i + "条sql");
            myTasks.add(myTask);
        }
        TaskBatchSendUtils.execute(myTasks, mailThreadPool, TaskBatchSendUtils::runSqlTask);
        return null;
    }

}